package com.tiger.jms.sample5;

import javax.ejb.EJBException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.InitialContext;

public class SenderBean implements javax.ejb.SessionBean {
	private javax.ejb.SessionContext sessionContext = null;
	private QueueConnection queueConnection = null;

	public void setSessionContext(javax.ejb.SessionContext sessionContext) {
		this.sessionContext = sessionContext;
	}

	protected void createQueueConnection() {
		try {
			InitialContext ctx = new InitialContext();
			QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) ctx.lookup("java:comp/env/jms/QueueCF");
			queueConnection = queueConnectionFactory.createQueueConnection();
		} catch (Exception e) {
			throw new EJBException(e);
		}
	}

	protected void closeQueueConnection() {
		try {
			if (queueConnection != null) {
				queueConnection.close();
				queueConnection = null;
			}
		} catch (Exception e) {
			throw new EJBException(e);
		}
	}

	public void ejbCreate() {
		createQueueConnection();
	}

	public void send(String message) {
		try {
			InitialContext ctx = new InitialContext();
			QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
			Queue queue = (Queue) ctx.lookup("java:comp/env/jms/sampleQueue");
			QueueSender queueSender = queueSession.createSender(queue);

			queueConnection.start();
			queueSender.send(queueSession.createTextMessage(message));

			queueSender.close();
			queueSession.close();
			queueConnection.stop();
		} catch (Exception e) {
			throw new EJBException(e);
		}
	}

	public void ejbPassivate() {
		closeQueueConnection();
	}

	public void ejbActivate() {
		createQueueConnection();
	}

	public void ejbRemove() {
		closeQueueConnection();
	}
}
